package main

import (
	"encoding/json"
	"fmt"
	"iot-base/common/config"
	"iot-base/common/multicast"
	"iot-base/common/netip"
	"net"
	"time"
)

type IPInfo struct {
	CurrentName string
	ID          string
	IPs         []netip.IPCfg
}

const REQ_IP = "ip"
const REQ_SET_IP = "setIP"

type Svr struct {
}

func (pSvr *Svr) Run(listenner *net.UDPConn, ifi net.Interface) {
	var buf [1024]byte
	for {
		nLen, pRemoteAddr, err := listenner.ReadFromUDP(buf[:])
		if err == nil {
			var mapValue map[string]interface{}
			errJson := json.Unmarshal(buf[0:nLen], &mapValue)
			if errJson == nil {
				ptype := mapValue["type"]
				switch ptype {
				case REQ_IP:
					ips, _ := netip.GetIPs()
					if ips != nil {
						var ipinfo IPInfo
						ipinfo.CurrentName = ifi.Name
						ipinfo.ID = config.SelfOption.ID
						ipinfo.IPs = ips
						jsonInfo, _ := json.Marshal(&ipinfo)
						if len(jsonInfo) > 0 {
							listenner.WriteTo(jsonInfo, pRemoteAddr)
						}

					}

				}
			}
		}
	}
}

func BeginDiscoverSvr(ip string, port int) {
	fmt.Println("***************************begin discorver svr****************")
	time.Sleep(20 * time.Second)
	multicast.Listen(ip, port, &Svr{})
}
